<template>
  <div class="dashboard-container">
    <!-- 欢迎卡片 -->
    <el-card class="welcome-card">
      <div class="welcome-content">
        <div class="left">
          <h2>欢迎使用党员发展管理系统</h2>
          <p class="date">{{ currentDate }}</p>
          <p class="summary">通过本系统，您可以方便地管理党员信息，进行角色分配和权限管理。</p>
        </div>
        <div class="right">
          <img :src="welcomeImage" alt="欢迎图" class="welcome-image" @error="handleImageError" />
        </div>
      </div>
    </el-card>

    <!-- 数据统计卡片 -->
    <div class="stat-cards">
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon" style="backgroundColor: #409EFF">
            <el-icon>
              <UserFilled />
            </el-icon>
          </div>
          <div class="stat-info">
            <p class="stat-title">用户总数</p>
            <p class="stat-value">{{ userCount }}</p>
          </div>
        </div>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon" style="backgroundColor: #F56C6C">
            <el-icon>
              <Promotion />
            </el-icon>
          </div>
          <div class="stat-info">
            <p class="stat-title">入党申请书总数</p>
            <p class="stat-value">{{ applicationCount }}</p>
          </div>
        </div>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon" style="backgroundColor: #67C23A">
            <el-icon>
              <Document />
            </el-icon>
          </div>
          <div class="stat-info">
            <p class="stat-title">入党志愿书总数</p>
            <p class="stat-value">{{ volunteerCount }}</p>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 用户角色分布图表 -->
    <el-card class="chart-card">
      <template #header>
        <div class="card-header">
          <h3>用户角色分布</h3>
        </div>
      </template>
      <div ref="roleChartRef" class="role-chart"></div>
    </el-card>

  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
import * as echarts from 'echarts';
import {
  UserFilled,
  Promotion,
  Document
} from '@element-plus/icons-vue';
// 使用新创建的dashboard-welcome.svg图片
import welcomeImage from '@/assets/dashboard-welcome.svg';
// 备用图片
import logoImage from '@/assets/logo.svg';
// 导入用户总数API
import { getUserCount } from '@/api/auth';
// 导入入党申请书API
import { getApplicationCount } from '@/api/partyApplication';
import { getVolunteerCount } from '@/api/volunteer';

const router = useRouter();
const imageLoadError = ref(false);
// 用户总数
const userCount = ref(0);
// 入党申请书总数
const applicationCount = ref(0);
// 入党志愿书总数
const volunteerCount = ref(0);

// 图表相关
const roleChartRef = ref(null);
let roleChart = null;

// 用户角色数据
const roleData = ref({
  '群众': 0,
  '入党积极分子': 0,
  '发展对象': 0,
  '预备党员': 0,
  '正式党员': 0
});

// 获取用户总数
const fetchUserCount = async () => {
  try {
    const response = await getUserCount({});
    if (response && response.data && response.data.data && response.data.data.count !== undefined) {
      userCount.value = response.data.data.count;
    }
  } catch (error) {
    console.error('获取用户总数失败:', error);
  }
};

// 获取入党申请书总数
const fetchApplicationCount = async () => {
  try {
    const response = await getApplicationCount({});
    if (response && response.data && response.data.data && response.data.data.count !== undefined) {
      applicationCount.value = response.data.data.count;
    }
  } catch (error) {
    console.error('获取入党申请书总数失败:', error);
  }
};

// 获取入党志愿书总数
const fetchVolunteerCount = async () => {
  try {
    const response = await getVolunteerCount({});
    if (response && response.data && response.data.data && response.data.data.count !== undefined) {
      volunteerCount.value = response.data.data.count;
    }
  } catch (error) {
    console.error('获取入党志愿书总数失败:', error);
  }
};

// 初始化图表
const initRoleChart = () => {
  if (roleChartRef.value) {
    roleChart = echarts.init(roleChartRef.value);
    updateRoleChart();
  }
};

// 更新图表数据
const updateRoleChart = () => {
  if (!roleChart) return;

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}人 ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center',
      data: Object.keys(roleData.value)
    },
    series: [
      {
        name: '用户角色分布',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['40%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: Object.entries(roleData.value).map(([name, value]) => ({
          name,
          value
        }))
      }
    ]
  };

  roleChart.setOption(option);
};

// 获取用户角色分布数据
const fetchRoleDistribution = async () => {
  try {
    var dirData = {};
    var userData = {
      politicalStatus: '群众'
    };
    const responseMass = await getUserCount(userData);
    userData.politicalStatus = '入党积极分子';
    const responseActivist = await getUserCount(userData);
    userData.politicalStatus = '发展对象';
    const responseDevelopment = await getUserCount(userData);
    userData.politicalStatus = '预备党员';
    const responseProbationary = await getUserCount(userData);
    userData.politicalStatus = '正式党员';
    const responseFormal = await getUserCount(userData);

    dirData.massCount = responseMass.data.data.count;
    dirData.activistCount = responseActivist.data.data.count;
    dirData.developmentCount = responseDevelopment.data.data.count;
    dirData.probationaryCount = responseProbationary.data.data.count;
    dirData.formalCount = responseFormal.data.data.count;
    roleData.value = {
      '群众': dirData.massCount || 0,
      '入党积极分子': dirData.activistCount || 0,
      '发展对象': dirData.developmentCount || 0,
      '预备党员': dirData.probationaryCount || 0,
      '正式党员': dirData.formalCount || 0
    };
    updateRoleChart();
  } catch (error) {
    console.error('获取用户角色分布失败:', error);
  }
};

// 监听窗口大小变化
const handleResize = () => {
  roleChart?.resize();
};

// 组件挂载时获取数据
onMounted(() => {
  fetchUserCount();
  fetchApplicationCount();
  fetchVolunteerCount();
  fetchRoleDistribution();
  initRoleChart();
  window.addEventListener('resize', handleResize);
});

// 组件卸载时清理
onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  roleChart?.dispose();
});

// 图片加载失败处理
const handleImageError = (e) => {
  imageLoadError.value = true;
  console.error('欢迎图片加载失败，使用备用图片');
  // 使用logo.svg作为备用图片
  e.target.src = logoImage;
};

// 当前日期
const currentDate = computed(() => {
  const date = new Date();
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    weekday: 'long'
  });
});

// 近期活动
const recentActivities = [
  {
    content: '系统功能更新说明会',
    time: '2023-05-20 14:00',
    type: 'primary',
    color: '#409EFF'
  },
  {
    content: '新用户培训会议',
    time: '2023-05-18 09:30',
    type: 'success',
    color: '#67C23A'
  },
  {
    content: '系统安全知识学习',
    time: '2023-05-15 15:00',
    type: 'info',
    color: '#909399'
  },
  {
    content: '社区服务活动',
    time: '2023-05-10 08:30',
    type: 'warning',
    color: '#E6A23C'
  }
];

// 通知公告
const notices = [
  {
    title: '关于用户信息更新的通知',
    category: '通知',
    type: 'primary',
    time: '2023-05-18'
  },
  {
    title: '系统维护安排',
    category: '通知',
    type: 'primary',
    time: '2023-05-15'
  },
  {
    title: '2023年第二季度工作总结',
    category: '文件',
    type: 'success',
    time: '2023-05-12'
  },
  {
    title: '用户管理规则（修订）',
    category: '规章',
    type: 'warning',
    time: '2023-05-10'
  },
  {
    title: '优秀用户评选结果公示',
    category: '公示',
    type: 'info',
    time: '2023-05-08'
  }
];
</script>

<style scoped>
.dashboard-container {
  padding: 16px;
}

.welcome-card {
  margin-bottom: 24px;
  border-radius: 8px;
}

.welcome-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.left {
  flex: 1;
  padding-right: 20px;
}

.left h2 {
  font-size: 24px;
  color: #303133;
  margin-top: 0;
  margin-bottom: 12px;
}

.date {
  font-size: 14px;
  color: #909399;
  margin-bottom: 16px;
}

.summary {
  font-size: 16px;
  color: #606266;
  margin-bottom: 24px;
  line-height: 1.6;
}

.right {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
}

.welcome-image {
  max-width: 100%;
  height: auto;
  max-height: 200px;
}

.stat-cards {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
  margin-bottom: 24px;
}

@media (max-width: 768px) {
  .welcome-content {
    flex-direction: column;
  }

  .left {
    padding-right: 0;
    margin-bottom: 20px;
  }

  .stat-cards {
    grid-template-columns: 1fr;
  }
}

.stat-card {
  border-radius: 8px;
}

.stat-content {
  display: flex;
  align-items: center;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
  font-size: 24px;
  margin-right: 16px;
}

.stat-info {
  flex: 1;
}

.stat-title {
  font-size: 14px;
  color: #909399;
  margin: 0 0 4px 0;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin: 0;
}

.info-section {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
  margin-bottom: 24px;
}

@media (max-width: 992px) {
  .info-section {
    grid-template-columns: 1fr;
  }
}

.info-card {
  border-radius: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.notice-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.notice-item {
  display: flex;
  align-items: center;
  font-size: 14px;
}

.notice-title {
  margin: 0 8px;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.notice-time {
  color: #909399;
}

.chart-card {
  margin-bottom: 24px;
  border-radius: 8px;
}

.role-chart {
  height: 400px;
  width: 100%;
}
</style>